<template>
	<view class="login-container">
		<uni-icons type="person-filled" size="100" color="#afafaf"></uni-icons>
		<button type="primary" class="btn-login" open-type="getUserInfo" @click="getUserProfile">一键登录</button>
		<view class="tips-text">
			登陆后尽享更多权益
		</view>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {

			};
		},
		computed: {
			...mapState('m_user', ['redirection'])
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirect']),
			// 用户授权之后,获取用户的基本信息
			getUserProfile() {
				uni.getUserProfile({
					desc: '请求授权', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写			
					success: (res) => {
						console.log(res);
			 		// 这部分是更新用户信息的		 res.userInfo 就是用户的基本信息
						this.updateUserInfo(res.userInfo)
						this.getToken(res)
						this.navigateBack()
					},
					fail: (res) => {
						return uni.$showMsg("已取消登录授权")
					}
				})
			},
			navigateBack() {
				if (this.redirection && this.redirection.openType === 'switchTab') {
					uni.switchTab({
						url:this.redirection.from,
						complete: () => {
							this.updateRedirect(null)
						}
					})
				}
			},
			// getUserInfo(e) {
			// 	// console.log(e);
			// 	// 判断用户是否授权成功
			// 	if(e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了授权')
			// 	 // 获取用户信息成功， e.detail.userInfo 就是用户的基本信息
			// 	    // console.log(e.detail.userInfo)
			// 			this.updateUserInfo(e.detail.userInfo)
			// 			this.getToken(e.detail)
			// },
			async getToken(info) {
				const [err, res] = await uni.login().catch(err => err)
				// 判断是否 uni.login() 调用失败
				if (err || res.errMsg !== 'login:ok') return uni.$showError('登录失败！')
				console.log(res);
				const query = {
					code: res.code,
					encryptedData: info.encryptedData,
					iv: info.iv,
					rawData: info.rawData,
					signature: info.signature
				}
				// 换取 token
				const {
					data: loginResult
				} = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				console.log(loginResult);
				if (loginResult.meta.status === 200) return uni.$showMsg('登录失败！')
				uni.$showMsg('登录成功')
				console.log(loginResult);
				this.updateToken(
					'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
					)
			},
		}
	}
</script>

<style lang="scss">
	.login-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding-top: 100px;

		.btn-login {
			margin: 10px 0;
			width: 60%;
			background-color: #C00000;
			border-radius: 30px;
		}

		.tips-text {
			color: gray;
		}
	}
</style>
